package com.zeyi.chat.controller;

import com.alibaba.fastjson.JSON;
import com.zeyi.chat.dto.Message;
import com.zeyi.chat.po.ChatGroup;
import com.zeyi.chat.utils.AvatarUtil;
import com.zeyi.chat.utils.SocketUtil;
import com.zeyi.chat.manager.StageManager;
import com.zeyi.chat.manager.UserManager;
import com.zeyi.chat.views.Alert;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.scene.control.TextField;
import javafx.scene.image.ImageView;
import javafx.scene.input.MouseEvent;
import javafx.scene.shape.Rectangle;
import javafx.stage.Stage;

import java.io.File;

/**
 * @author zeyi
 */
public class CreateGroupController {
    @FXML
    private ImageView groupAvatar;

    @FXML
    private TextField groupName;

    private String avatarPath = "/images/group/default.jpg";
    private File tmpFile;

    @FXML
    private void initialize() {
        Rectangle rectangle = new Rectangle(groupAvatar.prefWidth(-1), groupAvatar.prefHeight(-1));
        rectangle.setArcHeight(15);
        rectangle.setArcWidth(15);
        groupAvatar.setClip(rectangle);
    }

    @FXML
    public void minimize(MouseEvent mouseEvent) {
        Stage stage = (Stage) groupName.getScene().getWindow();
        stage.setIconified(true);
    }

    @FXML
    public void onClose(MouseEvent mouseEvent) {
        Stage stage = (Stage) groupName.getScene().getWindow();
        stage.close();
        StageManager.setGroupStage(null);
    }

    @FXML
    public void createGroup(ActionEvent actionEvent) {
        String text = groupName.getText();
        if (text.equals("")) {
            new Alert("请输入群名", StageManager.getGroupStage());
            return;
        }
        if (tmpFile != null) {
            avatarPath = AvatarUtil.copyAvatar(tmpFile, "group");
        }
        ChatGroup group = new ChatGroup(text, avatarPath, UserManager.getCurrentUser().getId());
        Message message = new Message("AddHandler/createGroup", "AddHandler/createGroup", UserManager.getCurrentUser(), JSON.toJSONString(group));
        SocketUtil.send(message);
    }

    @FXML
    public void chooseAvatar(MouseEvent mouseEvent) {
        tmpFile = AvatarUtil.chooseAvatar(StageManager.getGroupStage(), groupAvatar, "group");
    }
}
